﻿namespace ThingsGateway.Foundation
{
    /// <summary>
    /// 所有数据转换类的静态辅助方法<br />
    /// </summary>
    public static class ByteTransformHelper
    {
        /// <summary>使用指定的转换方法，来获取到实际的结果对象内容</summary>
        /// <typeparam name="TIn">输入类型</typeparam>
        /// <param name="result">原始的结果对象</param>
        /// <param name="trans">转换方法，从类型TIn转换拿到Result的TResult的泛型委托</param>
        /// <returns>类型为TResult的对象</returns>
        public static Result GetResultFromOther<TIn>(
          Result<TIn> result,
          Func<TIn, Result> trans)
        {
            return !result.IsSuccess ? result : trans(result.Content);
        }
        /// <summary>使用指定的转换方法，来获取到实际的结果对象内容，所转换的规则</summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <typeparam name="TIn">输入类型</typeparam>
        /// <param name="result">原始的结果对象</param>
        /// <param name="trans">转换方法，从类型TIn转换拿到TResult的泛型委托</param>
        /// <returns>类型为TResult的对象</returns>
        public static Result<TResult> GetSuccessResultFromOther<TResult, TIn>(
          Result<TIn> result,
          Func<TIn, TResult> trans)
        {
            return !result.IsSuccess ? Result.CreateFailedResult<TResult>(result) : Result.CreateSuccessResult<TResult>(trans(result.Content));
        }
        /// <summary>结果转换操作的基础方法，需要支持类型，及转换的委托，并捕获转换时的异常方法</summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="result">源</param>
        /// <param name="translator">实际转换的委托</param>
        /// <returns>转换结果</returns>
        public static Result<TResult> GetResultFromBytes<TResult>(
          Result<byte[]> result,
          Func<byte[], TResult> translator)
        {
            try
            {
                return result.IsSuccess ? Result.CreateSuccessResult<TResult>(translator(result.Content)) : Result.CreateFailedResult<TResult>(result);
            }
            catch (Exception ex)
            {
                Result<TResult> resultFromBytes = new Result<TResult>
                {
                    Message = string.Format("{0} {1} : Length({2}) {3}", Resource.DataTransformError, result.Content.ToHexString(), result.Content.Length, ex.Message)
                };
                return resultFromBytes;
            }
        }
    }
}